﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Models;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    /// <summary>
    /// 设备类型接口
    /// </summary>
    [DynamicApiController]
    public class DeviceTypeController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public DeviceTypeController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 设备类型列表
        /// </summary>
        /// <param name="eid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid)
        {
            JArray data = GetDeviceTypeTree(eid, 0).Result;
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        [NonAction]
        public async Task<JArray> GetDeviceTypeTree(long eid, long pid)
        {
            JArray data = new();
            List<DeviceType> devicetypes = await db.Queryable<DeviceType>().Where(dt => dt.IsDel == 0).Where(dt => dt.IsDel == 0).Where(dt => dt.Eid == eid && dt.ParentId == pid).OrderBy(dt => dt.SortId, OrderByType.Asc).ToListAsync();
            if (devicetypes != null && devicetypes.Count > 0)
            {
                foreach (var devicetype in devicetypes)
                {
                    JObject jo_menu = JObject.FromObject(devicetype);
                    jo_menu.Add("children", GetDeviceTypeTree(eid, devicetype.Id).Result);
                    data.Add(jo_menu);
                }
            }
            return data;
        }

        /// <summary>
        /// 根据子ID获取所有父ID
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetallparentbychildrenid([FromForm] long eid, [FromForm] long id)
        {
            await GetAllParent(eid, id);

            JObject data = new();
            devicetypes.Reverse();
            data.Add("parent_devicetypes", JArray.FromObject(devicetypes));
            List<DeviceType> children_devicetypes = await db.Queryable<DeviceType>().Where(dt => dt.IsDel == 0).Where(dt => dt.Eid == eid && dt.ParentId == id).OrderBy(dt => dt.SortId, OrderByType.Asc).ToListAsync();
            data.Add("children_devicetypes", children_devicetypes == null ? null : JArray.FromObject(children_devicetypes));
            return new JsonResult(new { status = "success", message = "获取所有父类成功", code = 1, data });
        }

        private readonly List<DeviceType> devicetypes = new(); // 所有设备类型父设备类型
        [NonAction]
        public async Task GetAllParent(long eid, long id)
        {
            // 查询当前节点信息
            DeviceType devicetype = await db.Queryable<DeviceType>().Where(dt => dt.IsDel == 0).Where(dt => dt.Eid == eid && dt.Id == id).SingleAsync();
            if (devicetype != null)
            {
                devicetypes.Add(devicetype);
                await GetAllParent(eid, devicetype.ParentId);
            }
        }

        /// <summary>
        /// 异步获取子设备类型
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetchildren([FromForm] long eid, [FromForm] long parent_id)
        {
            List<DeviceType> devicetypes = await db.Queryable<DeviceType>().Where(dt => dt.IsDel == 0).Where(dt => dt.Eid == eid && dt.ParentId == parent_id).OrderBy("sort_id asc").ToListAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = devicetypes,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 设备类型增加
        /// </summary>
        /// <param name="strjsondevicetypes"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] long eid, [FromForm] string strjsondevicetypes)
        {
            List<DeviceType> devicetypes = JsonConvert.DeserializeObject<List<DeviceType>>(strjsondevicetypes);
            // 根据索引排序
            devicetypes.ForEach(dt => dt.SortId = devicetypes.IndexOf(dt) + 1);
            List<DeviceType> insertDeviceTypes = new();
            List<DeviceType> updateDeviceTypes = new();
            foreach (var devicetype in devicetypes)
            {
                if (devicetype.Id == 0)
                {
                    // 增加
                    insertDeviceTypes.Add(devicetype);
                }
                else
                {
                    // 更新
                    updateDeviceTypes.Add(devicetype);
                }
            }
            JObject data = new();
            if (insertDeviceTypes.Count > 0)
            {
                // 执行插入操作
                int insertAffrows = await db.Insertable<DeviceType>(insertDeviceTypes).ExecuteCommandAsync();
                data.Add("insertAffrows", insertAffrows);
            }
            if (updateDeviceTypes.Count > 0)
            {
                // 执行更新操作
                int updateAffrows = await db.Updateable<DeviceType>(updateDeviceTypes).ExecuteCommandAsync();
                data.Add("updateAffrows", updateAffrows);
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDelete([FromForm] long eid, [FromForm] long id)
        {
            // 该设备类型下有子设备类型不让删除
            bool halDevicetype = await db.Queryable<DeviceType>().Where(dt => dt.IsDel == 0).Where(dt => dt.Eid == eid && dt.ParentId == id).AnyAsync();
            if (halDevicetype)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "该设备类型下拥有子设备类型，不允许删除",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            int affrows = await db.Deleteable<DeviceType>().Where(dt => dt.Eid == eid && dt.Id == id).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = affrows,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="devicetype"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdate([FromForm] long eid, [FromForm] DeviceType devicetype)
        {
            int affrows = await db.Updateable<DeviceType>(devicetype).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = affrows,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 设备类型查看
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShow([FromForm] long eid, [FromForm] long id)
        {
            DeviceType devicetype = await db.Queryable<DeviceType>().Where(dt => dt.IsDel == 0).Where(dt => dt.Eid == eid && dt.Id == id).SingleAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = devicetype,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 拖拽
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="strjsondevicetypes"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDrag([FromForm] long eid, [FromForm] string strjsondevicetypes)
        {
            List<DeviceType> devicetypes = JsonConvert.DeserializeObject<List<DeviceType>>(strjsondevicetypes);
            devicetypes.ForEach(dt => dt.SortId = devicetypes.IndexOf(dt) + 1);
            int affrows = await db.Updateable<DeviceType>(devicetypes).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = affrows,
                Errors = "拖拽更新成功",
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
